package christheadimg;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

public class CreateHeadImg extends HttpServlet{
		
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		try {
			if(isEmpty(action)){
				Cookie[] cookies = request.getCookies();
				if(cookies != null){
					for (int i = 0; i < cookies.length; i++) {
						if(cookies[i].getName().equals("create_headimg")){
							request.setAttribute("img", cookies[i].getValue());
						}
					}
				}
				request.getRequestDispatcher("index.jsp").forward(request, response);
				return;
			}
			if(action.equals("rd")){
				rd(request,response);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public boolean isEmpty(Object obj){
		return obj == null || "".equals(obj);
	}
	
	public void rd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		String code = request.getParameter("code");
		System.out.println("code is "+code);
		if(isEmpty(code)){
			response.getWriter().write("获取用户信息失败");
			return;
		}
		String appid = "wx4d43eae9f950c665";
		String secret = "f152b7fd3279de36060c3434296cbc51";
		Map<String, Object> accessTokenMap = getAccessToken(appid, secret, code);
		if(accessTokenMap == null){
			response.getWriter().write("获取用户信息失败");
			return;
		}
		String access_token = (String)accessTokenMap.get("access_token");
		if(isEmpty(access_token)){
			response.getWriter().write("获取用户信息失败");
			return;
		}
		String openid = (String)accessTokenMap.get("openid");
		Map<String, Object> userinfo = getUserinfo(access_token,openid);
		String headimgurl = (String) userinfo.get("headimgurl");
		BufferedImage image = ImageIO.read(new URL(headimgurl));
		ImageIO.write(image, "png", new File(request.getServletContext().getRealPath("images/"+openid+".png")));
		Cookie cookie = new Cookie("create_headimg", (String)userinfo.get("openid"));
		cookie.setMaxAge(1000*60*60*24*365*10);
		cookie.setPath("/");
		response.addCookie(cookie);
		response.sendRedirect("index.html");
	}
		
	
	
	/**
	 * 获取access_token
	 * @return
	 */
	private Map<String, Object> getAccessToken(String appid,String secret,String code){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("appid", appid);
		param.put("secret", secret);
		param.put("code", code);
		param.put("grant_type", "authorization_code");
		String result = HttpUrlUtils.get("https://api.weixin.qq.com/sns/oauth2/access_token", param);
		return JSON.parseObject(result);
	}
	
	/**
	 * 获取用户信息
	 * @param access_token
	 * @param openid
	 * @return
	 */
	private Map<String,Object> getUserinfo(String access_token,String openid){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("access_token", access_token);
		param.put("openid", openid);
		param.put("lang", "zh_CN");
		String result = HttpUrlUtils.get("https://api.weixin.qq.com/sns/userinfo", param);
		return JSON.parseObject(result);
	}
}
